package xxl

import (
	"github.com/xxl-job/xxl-job-executor-go"
	"github.com/zeromicro/go-zero/core/logx"
	"go-zero-demo/common/tools"
	"go-zero-demo/user-api/internal/config"
	"strconv"
)

func InitXxlJob(conf config.Config) (xxl.Executor, error) {
	jobConfig := conf.XxlConf
	// 获取正在使用的IP地址
	ip, _ := tools.GetActiveIP()
	//初始化执行器
	exec := xxl.NewExecutor(
		xxl.ServerAddr(jobConfig.ServerAddr),
		//请求令牌(默认为空)
		xxl.AccessToken(jobConfig.AccessToken),
		//可自动获取
		xxl.ExecutorIp(ip),
		// 默认9999（服务启动port必需一至）
		xxl.ExecutorPort(strconv.Itoa(conf.Port)),
		//执行器名称
		xxl.RegistryKey(jobConfig.RegistryKey),
		//自定义日志
		xxl.SetLogger(&logger{}),
	)
	exec.Init()
	////设置日志查看handler
	exec.LogHandler(func(req *xxl.LogReq) *xxl.LogRes {
		return &xxl.LogRes{Code: xxl.SuccessCode, Msg: "", Content: xxl.LogResContent{
			FromLineNum: req.FromLineNum,
			ToLineNum:   2,
			LogContent:  "xxl-job",
			IsEnd:       true,
		}}
	})

	return exec, nil
}

// xxl.Logger接口实现
type logger struct{}

func (l *logger) Info(format string, a ...interface{}) {
	logx.Debug("xxl job info log -", format, a)
}

func (l *logger) Error(format string, a ...interface{}) {
	logx.Errorf("xxl job error log -", format, a)
}
